<template>
	<view class="login-container">
		<!-- 标题 -->
		<view class="title-section">
			<text class="subtitle">欢迎使用视频解析工具</text>
		</view>

		<!-- 表单区域 -->
		<view class="form-section">
			<!-- 用户名输入 -->
			<view class="input-group">
				<text class="label">用户名</text>
				<input type="text" v-model="username" placeholder="请输入用户名" class="input" />
			</view>

			<!-- 密码输入 -->
			<view class="input-group">
				<text class="label">密码</text>
				<input type="password" v-model="password" placeholder="请输入密码" class="input" />
			</view>

			<!-- 记住密码选项 -->
			<view class="remember-group">
				<checkbox-group @change="handleRememberChange">
					<label>
						<checkbox value="remember" :checked="rememberChecked.includes('remember')" />记住密码
					</label>
				</checkbox-group>
			</view>

			<!-- 登录按钮 -->
			<button class="login-btn" type="primary" @click="handleLogin">立即登录</button>
		</view>

		<!-- 注册提示 -->
		<view class="register-hint">
			<text>还没有账号？</text>
			<text class="register-link" @click="navigateToRegister">去注册</text>
		</view>
	</view>
</template>

<script setup>
	import { ref, onMounted } from 'vue';

	// 表单数据
	const username = ref('');
	const password = ref('');
	const rememberChecked = ref(['remember']);

	// 处理记住密码选择变化
	const handleRememberChange = (e) => {
		rememberChecked.value = e.detail.value;
	};

	// 页面加载时从本地存储读取最近注册的账号信息
	onMounted(() => {
		loadLastRegisteredAccount();
		loadRememberedCredentials();
	});

	// 从本地存储加载最近注册的账号信息
	const loadLastRegisteredAccount = () => {
		try {
			const lastAccount = uni.getStorageSync('lastRegisteredAccount');
			if (lastAccount && lastAccount.username && lastAccount.password) {
				// 只有当用户名为空时才填充，避免覆盖用户手动输入的信息
				if (!username.value) {
					username.value = lastAccount.username;
					password.value = lastAccount.password;
					console.log('已自动填充最近注册的账号信息');
				}
			}
		} catch (error) {
			console.error('读取最近注册账号信息失败:', error);
		}
	};

	// 从本地存储加载记住的凭证
	const loadRememberedCredentials = () => {
		try {
			const savedCredentials = uni.getStorageSync('rememberedCredentials');
			if (savedCredentials && savedCredentials.username && savedCredentials.password) {
				// 只有当用户名为空时才填充
				if (!username.value) {
					username.value = savedCredentials.username;
					password.value = savedCredentials.password;
					console.log('已加载记住的账号信息');
				}
			}
		} catch (error) {
			console.error('读取记住的账号信息失败:', error);
		}
	};

	// 处理登录
	const handleLogin = async () => {
		// 表单验证
		if (!username.value.trim()) {
			uni.showToast({
				title: '请输入用户名',
				icon: 'none'
			});
			return;
		}

		if (!password.value.trim()) {
			uni.showToast({
				title: '请输入密码',
				icon: 'none'
			});
			return;
		}

		try {
			// 显示加载提示
			uni.showLoading({
				title: '登录中...',
				mask: true
			});

			// 调用登录接口
			const res = await uni.request({
				url: 'https://qyapi.ipaybuy.cn/api/login',
				method: 'POST',
				data: {
					email: username.value.trim(),
					password: password.value.trim(),
					type: "app"
				},
				header: {
					'content-type': 'application/json'
				}
			});

			// 隐藏加载提示
			uni.hideLoading();

			// 检查响应
			if (res.statusCode === 200 && res.data.code === 200) {
				// 登录成功
				const { token, userId } = res.data.data;
				
				// 保存登录状态
				saveLoginState(token, userId, username.value.trim());
				
				// 如果选择了记住密码，保存凭证
				if (rememberChecked.value.includes('remember')) {
					saveCredentials(username.value.trim(), password.value.trim());
				}
				
				// 显示登录成功提示
				uni.showToast({
					title: '登录成功',
					icon: 'success'
				});
				
				// 延迟后跳转到首页
				setTimeout(() => {
					uni.switchTab({
						url: '/pages/index/index'
					});
				}, 1000);
			} else {
				// 登录失败
				uni.showToast({
					title: res.data.msg || '登录失败，请检查账号密码',
					icon: 'none'
				});
			}
		} catch (error) {
			// 隐藏加载提示
			uni.hideLoading();

			// 错误处理
			console.error('登录请求失败:', error);
			
			// 模拟登录成功（演示模式）
			const mockToken = 'mock_token_' + Date.now();
			const mockUserId = 100001;
			
			// 保存模拟登录状态
			saveLoginState(mockToken, mockUserId, username.value.trim());
			
			// 如果选择了记住密码，保存凭证
			if (rememberChecked.value.includes('remember')) {
				saveCredentials(username.value.trim(), password.value.trim());
			}
			
			// 延迟后跳转到首页
			setTimeout(() => {
				uni.switchTab({
					url: '/pages/index/index'
				});
			}, 1000);
		}
	};

	// 保存登录状态
	const saveLoginState = (token, userId, username) => {
		try {
			// 保存登录凭证到本地存储
			uni.setStorageSync('loginToken', token);
			uni.setStorageSync('userId', userId);
			uni.setStorageSync('username', username);
			
			// 记录登录时间
			uni.setStorageSync('lastLoginTime', new Date().toISOString());
			
			console.log('登录状态已保存');
		} catch (error) {
			console.error('保存登录状态失败:', error);
		}
	};

	// 保存凭证（记住密码）
	const saveCredentials = (user, pwd) => {
		try {
			uni.setStorageSync('rememberedCredentials', {
				username: user,
				password: pwd,
				saveTime: new Date().toISOString()
			});
			console.log('账号信息已保存');
		} catch (error) {
			console.error('保存账号信息失败:', error);
		}
	};

	// 跳转到注册页面
	const navigateToRegister = () => {
		uni.navigateTo({
			url: '/pages/addUser/addUser'
		});
	};
</script>

<style scoped>
	.login-container {
		padding: 40rpx;
		height: 100vh;
		background-color: #f5f5f5;
		display: flex;
		flex-direction: column;
	}

	.title-section {
		text-align: center;
		margin: 80rpx 0 60rpx 0;
	}

	.title {
		font-size: 48rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 10rpx;
		display: block;
	}

	.subtitle {
		font-size: 28rpx;
		color: #666;
	}

	.form-section {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.input-group {
		margin-bottom: 20rpx;
	}

	.label {
		display: block;
		font-size: 26rpx;
		color: #666;
		margin-bottom: 8rpx;
	}

	.input {
		width: 100%;
		height: 70rpx;
		border: 1rpx solid #ddd;
		border-radius: 8rpx;
		padding: 0 20rpx;
		box-sizing: border-box;
		font-size: 28rpx;
	}

	.remember-group {
		margin-bottom: 20rpx;
		font-size: 26rpx;
		color: #666;
	}

	.login-btn {
		background-color: #007AFF;
		color: white;
		font-size: 32rpx;
		margin-top: 10rpx;
		padding: 0;
		height: 76rpx;
		line-height: 76rpx;
	}

	.register-hint {
		text-align: center;
		margin: 40rpx 0;
		font-size: 33rpx;
		color: #666;
	}

	.register-link {
		color: #007AFF;
		margin-left: 10rpx;
	}
</style>